<template>
    <x-popup v-model="showModal" height="70vh" class="x-regions">
        <view class="flex bg-white p-4 grid-gap-2">
            <view class="h9 font-weight-600" :class="{ 'text-primary': item.id }" v-for="(item, index) in selected"
                :key="index" @tap="clearSelected(index)">{{ item.title }}
            </view>
        </view>
        <view class="flex-1 flex flex-column overflow-y-auto">
            <view class="p-4 flex flex-column grid-gap-2" v-for="(data, pinyin_prefix) in viewData"
                :key="pinyin_prefix">
                <text class="pinyin_prefix h10 font-weight-600">{{ pinyin_prefix }}</text>
                <view class="grid-columns-6  grid-gap-2">
                    <view class="grid-column-2 bg-white rounded-2 p-2 text-center h9 font-weight-600"
                        v-for="item in data" :key="item.id" @tap="selectedRegions(item)">
                        {{ item.title }}</view>
                </view>
            </view>
        </view>
        <view class="p-4 flex" v-if="props.checkStrictly">
            <button class="flex-1 btn-primary btn-round" @click="eventSelected"
                :disabled="!selected[0] && !selected[0].id">确定</button>
        </view>
        <view class="pb-safe-area"></view>
    </x-popup>
</template>
<script setup lang="ts">
import { ref, onMounted,defineProps } from 'vue';
import { $api, $message } from "@/utils";
const props = withDefaults(defineProps<{
    checkStrictly?: boolean
}>(), {
    checkStrictly: false
});
const showModal = ref(false);
const selected = ref([
    {
        title: '省'
    }
]);
const level = ref(3);
const viewData = ref([]);
const regions = ref([]);
const emit = defineEmits(['selected']);
const setViewData = (data: any) => {
    let d:any = {};
    for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (!d[item.pinyin_prefix]) {
            d[item.pinyin_prefix] = [];
        }
        d[item.pinyin_prefix].push({
            id: item.id,
            title: item.title,
            level: item.level,
            index: i,
        });
    }
    const sortedKeys = Object.keys(d).sort();
    let sortedObj: any = {};
    sortedKeys.forEach(key => {
        sortedObj[key] = d[key];
    });
    viewData.value = sortedObj;
    if (data.length===1) {
        selectedRegions(viewData.value[0]);
    }
}
const show = (options: any) => {
    if (options) {
        if (options.level !== undefined) {
            level.value = options.level;
        }
    }
    showModal.value = true;
}
const hide = () => {
    showModal.value = false;
}
const toggle = () => {
    showModal.value = !showModal.value;
}
const clearSelected = (level: any) => {
    selected.value.splice(level);
    let indexArr = selected.value.map((item: any) => {
        if (item.index !== undefined) {
            return item.index;
        }
    }).filter((item: any) => item !== undefined);
    // 去除undefined
    let data = regions.value;
    for (let i = 0; i < indexArr.length; i++) {
        let index = indexArr[i];
        if (data[index].children) {
            data = data[index].children;
        } else {
            return eventSelected();
        }
    }
    selected.value.push({
        title: getLevelText(level)
    });
    setViewData(data);
}
const getLevelText = (level: number) => {
    switch (level) {
        case 0:
            return '省';
        case 1:
            return '市';
        case 2:
            return '区';
        case 3:
            return '街道';
        default:
            return '';
    }
}
const selectedRegions = (item: any) => {
    if(!item)return;
    selected.value[item.level] = item;
    let indexArr = selected.value.map((item: any) => {
        if (item.index !== undefined) {
            return item.index;
        }
    }).filter((item: any) => item !== undefined);
    // 去除undefined
    let data = regions.value;
    for (let i = 0; i < indexArr.length; i++) {
        let index = indexArr[i];
        if (data[index].children && data[index].level < level.value) {
            data = data[index].children;
        } else {
            return eventSelected();
        }
    }
    selected.value.push({
        title: getLevelText(item.level + 1)
    });
    setViewData(data);
}
const search = (region: any) => {
    let data = regions.value;
    for (let i = 0; i < data.length; i++) {
        const provinceItem = data[i];
        if (provinceItem.title.includes(region.province)) {
            selected.value[provinceItem.level] = {
                id: provinceItem.id,
                title: provinceItem.title,
            };
            for (let j = 0; j < provinceItem.children.length; j++) {
                const cityItem = provinceItem.children[j];
                if (cityItem.title.includes(region.city)) {
                    selected.value[cityItem.level] = {
                        id: cityItem.id,
                        title: cityItem.title,
                    };
                    for (let k = 0; k < cityItem.children.length; k++) {
                        const areaItem = cityItem.children[k];
                        if (areaItem.title.includes(region.area)) {
                            selected.value[areaItem.level] = {
                                id: areaItem.id,
                                title: areaItem.title,
                            };
                            for (let l = 0; l < areaItem.children.length; l++) {
                                const streetItem = areaItem.children[l];
                                if (streetItem.title.includes(region.street)) {
                                    selected.value[streetItem.level] = {
                                        id: streetItem.id,
                                        title: streetItem.title,
                                    };
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    break;
                }
            }
            break;
        }
    }
    eventSelected();
}
const eventSelected = () => {
    let result:any = {
        province_id: selected.value[0].id,
        province: selected.value[0].title,
    };
    if (selected.value[1] && selected.value[1].id) {
        result.city_id = selected.value[1].id;
        result.city = selected.value[1].title;
    }
    if (selected.value[2] && selected.value[2].id) {
        result.area_id = selected.value[2].id;
        result.area = selected.value[2].title;
    }
    if (selected.value[3] && selected.value[3].id) {
        result.street_id = selected.value[3].id;
        result.street = selected.value[3].title;
    }
    emit('selected', result);
    selected.value = [
        {
            title: '省'
        }
    ];
    setViewData(regions.value);
    hide();
}
onMounted(() => {
    $api.Regions.getRegions().then((data: any) => {
        regions.value = data;
        setViewData(regions.value);
    }).catch((err: any) => {
        console.log(err);
        $message.error(err.msg);
    });
});
defineExpose({
    show,
    hide,
    toggle,
    search,
});
</script>
<style lang="scss" scoped>
.x-regions {
    --x-popup-bg: #{$uni-bg-color-grey};
}

.pinyin_prefix {
    // 大写
    text-transform: uppercase;
}
</style>